package com.jessechanrui.template.req15;

import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.agree.bos.bpbc.service.IBpbcCsvSerevice;
import com.agree.bos.bpbc.service.IBpbcPdfSerevice;
import com.agree.bos.nsh.model.AfaCzedxzpTxnjnl;
import com.agree.bos.nsh.service.IBlackAshListSerevice;
import com.agree.framework.dao.entity.Page;
import com.agree.framework.exception.AppException;
import com.agree.framework.web.service.base.BaseService;
import com.agree.util.DateUtil;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
//import com.itextpdf.text.pdf.qrcode.BitMatrix;
//import com.itextpdf.text.pdf.qrcode.EncodeHintType;
//import com.itextpdf.text.pdf.qrcode.ErrorCorrectionLevel;

public class BpbcCsvSerevice extends BaseService implements IBpbcCsvSerevice{
	private Logger logger = Logger.getLogger(BpbcCsvSerevice.class);


	/**
	 * @category BEC_SCPDF 银行函证PDF生成
	 * @param busidate
	 *            入参|业务日期|{@link String}
	 * @param confirmno 
	 *            入参|函证编号|{@link String}
	 * @param tenantname
	 *            入参|会计师事务所名称|{@link String}
	 * @param enddate
	 *            入参|截止日期|{@link String}
	 * @param organizationname           
	 *            入参|单位名称|{@link String}
	 * @param values
	 *            入参|函证项信息|{@link cn.com.agree.afa.svc.javaengine.context.JavaList}
	 * @param outputfilePath
	 *            入参|PDF存放文件路径|{@link String}
	 * @since error 出参|PDF生成结果true/false|{@link String}
	 * @return 0 失败<br/>
	 *         1 成功<br/>
	 * @throws DocumentException 
	 * @throws IOException 
	 */
	@Override
	public boolean createCsv(JSONObject json) throws Exception {
		//AppLogger.info("业务日期---------：" + busi_date);
		//AppLogger.info("函证编号---------：" + confirmno);
		//AppLogger.info("会计师事务所名称---------：" + tenantname);
		//AppLogger.info("起始日期---------：" + startdate);
		//AppLogger.info("截止日期---------：" + enddate);
		//AppLogger.info("单位名称---------：" + organizationname);
		//AppLogger.info("函证项信息---------：" + String.valueOf(values));
		
		//*************************生成PDF文件
		//AppLogger.info("*************************生成PDF文件start");
		//页面大小
		String hzbh = (String) json.get("hzbh");//函证编号
		String recvdate = (String) json.get("recvdate");//函证接收日期
		String organizationname = (String) json.get("organizationname");//单位名称
		String tenantname = (String) json.get("tenantname");//会计师事务所名称
		System.out.print("函证编号---------：" + hzbh);
		System.out.print("函证编号---------：" + json);
		
		String confirmbegindate = (String) json.get("confirmbegindate");//起始日期
		String confirmenddate = (String) json.get("confirmenddate");//截止日期
		String pdffilepath = (String) json.get("pdffilepath");//文件目录
		String csvEncode = (String) json.get("csvEncode");//文件编码

		String startdate;
		String busi_date = null;
		Rectangle rect = new Rectangle(PageSize.A4);//文档竖向
//		String outputfilePath = "C:/Users/A9010012/Desktop";
		String flag = (String) json.get("flag");//文件目录
		String outputfilePath = "";
		if(flag.equals("update")){
			outputfilePath = pdffilepath+"(update)"+hzbh+".csv";
		}else{
			outputfilePath = pdffilepath+hzbh+".csv";
		}
		
		byte[] bomByte = null;
		String bomStr = "";

		//如果没有则创建
		File saveDir = new File(outputfilePath);
		File dir = saveDir.getParentFile();
		if(!dir.exists()){
			dir.mkdirs();			
		}
		
		File file = new File(outputfilePath);
		String _strToFile_ = "";
		BufferedWriter bufout = null;
		boolean append = false;
		if (file.exists()) {
			append = true;
		}
		
		if(json != null && !json.equals("{}")){
			PdfPTable table = null;
//			List result = null;
			//银行存款函证
			List bankdeposit_colName = Arrays.asList("账户名称","银行账号","币种","利率","账户类型","账户余额","是否属于资金归集（资金池或其他资金管理）账户","起始日期","终止日期","是否存在冻结、担保或其他使用限制（如是，请注明相关情形）","备注");//
			//银行借款函证
			List bankloan_colName = Arrays.asList("借款人名称","借款账号","币种","余额","借款日期","到期日期","利率","抵（质）押品/担保人","备注");
			//期间注销账户函证
			List closeacctno_colName = Arrays.asList("账户名称","银行账号","币种","注销账户日");
			//公司贷款方委托贷款函证
			List creditloan_colName = Arrays.asList("账户名称","银行结算账号/借据编号/贷款账号","资金借入方","币种","利率","余额","贷款起止日期","备注");//
			//公司借款方委托贷款函证
			List debtorloan_colName = Arrays.asList("账户名称","银行结算账号/借据编号/贷款账号","资金借出方","币种","利率","余额","贷款起止日期","备注");//
			//银行受益人担保函证
			List ensurefavoree_colName = Arrays.asList("被担保人","担保方式","币种","担保余额","担保到期日","担保合同编号","备注");
			//银行担保函证
			List givesecurity_colName = Arrays.asList("被担保人","担保方式","币种","担保金额","担保到期日","担保合同编号","备注");
			//未支付银行承兑汇票函证
			List unpaidaccance_colName = Arrays.asList("银行承兑汇票号码","结算账户账号","币种","票面金额","出票日","到期日","抵（质）押品");
			//未到期商业汇票函证
			List notduetradebill_colName = Arrays.asList("商业汇票号码","承兑人名称","币种","票面金额","出票日","到期日","贴现日","贴现率","贴现净额");
			//银行托收商业汇票函证
			List colltradebill_colName = Arrays.asList("商业汇票号码","承兑人名称","币种","票面金额","出票日","到期日");
			//不可撤销信用证函证
			List irrofcredit_colName = Arrays.asList("信用证号码","受益人","币种","信用证金额","到期日","未使用金额");
			//外汇买卖合约函证
			List foreigndealcon_colName = Arrays.asList("类    别","合约号码","贵行卖出币种","贵行买入币种","未履行的合约买卖金额","汇率","交收日期");
			//证券产权文件函证
			List secquityfile_colName = Arrays.asList("证券或其他产权文件名称","证券代码或产权文件编号","数量","币种","金额");
			//未到期银行理财产品函证
			List notduefinalpro_colName = Arrays.asList("产品名称","产品类型（封闭式/开放式）","币种","持有份额","产品净值","购买日","到期日","是否被用于担保或存在其他使用限制");
			//资金归集账户信息函证
			List cashconacctinfo_colName = Arrays.asList("序号","资金提供机构名称(即拨入资金的具体机构)","资金提供机构账号","资金使用机构名称(即向该具体机构拨出资金)","资金使用机构账号","币种","截至函证基准日拨入或拨出资金余额(拨出填列正数，拨入填列负数)","备注");
			//其他函证
			List otherinfo_colName = Arrays.asList("其他");
			
			
			//其他函证1
			List otherinfo1_colName = Arrays.asList("客户名称","类别","合约号码","贵行支付币种","贵行收取币种","未履行的合约金额","到期日");
			//其他函证2
			List otherinfo2_colName = Arrays.asList("客户名称","类别","合约号码","期权结构","未履行的合约币种","未履行的合约金额","行权价格","到期日");
			//其他函证3
			List otherinfo3_colName = Arrays.asList("客户名称","类别","合约号码","贵行支付利率","贵行收取利率","未履行的合约币种","未履行的合约金额","到期日");
			//其他函证4
			List otherinfo4_colName = Arrays.asList("客户名称","类别","合约号码","期权结构","未履行的合约币种","未履行的合约金额","行权价格","到期日");
			
			//其他函证5
			List otherinfo5_colName = Arrays.asList("借款人名称","借款账号","币种","余额","借款日期","到期日期","利率","抵(质)押品担保人","备注");
			
			//其他函证6
			List otherinfo6_colName = Arrays.asList("备注");
			
//			System.out.print(json.get("bankdeposit_num"));
			
			for (int i = 0; i < (int)json.get("hzxnum"); i++) {
				List a = (List)json.get("hzxinfo");
				
//				System.out.print("******"+a.get(i).toString().replace("[", "").replace("]", "").replace("\"", ""));
//				System.out.print("******"+a.get(i).toString().replace("[", "").replace("]", "").replace("\"", ""));
//				switch(a.get(i).toString().replace("[", "").replace("]", "").replace("\"", "")){
				switch(a.get(i).toString()){
					case "[\"1\"]":
						if((int)json.get("bankdeposit_num") > 0){
							String title = "1.银行存款\n";
							List result = (List)json.get("bankdeposit");
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,bankdeposit_colName);
						}else if((int)json.get("bankdeposit_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							String title = "1.银行存款\n";
							for (int j = 1; j < bankdeposit_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,bankdeposit_colName);
						}
					break;
					case "[\"2\"]":
						if((int)json.get("bankloan_num") > 0){
							List result = (List)json.get("bankloan");
							String title = "2.银行借款\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,bankloan_colName);
						}else if((int)json.get("bankloan_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < bankloan_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "2.银行借款\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,bankloan_colName);
						}
					break;
					case "[\"3\"]":
						if((int)json.get("closeacctno_num") > 0){
							String begdate = DateUtil.formatDate(confirmbegindate, "yyyymmdd", "yyyy年mm月dd日");
							String enddate = DateUtil.formatDate(confirmenddate, "yyyymmdd", "yyyy年mm月dd日");
							List result = (List)json.get("closeacctno");
							String title = "3.自"+begdate+"起至"+enddate+"期间内注销的银行存款账户\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,closeacctno_colName);
						}else if((int)json.get("closeacctno_num") == 0){
							String begdate = DateUtil.formatDate(confirmbegindate, "yyyymmdd", "yyyy年mm月dd日");
							String enddate = DateUtil.formatDate(confirmenddate, "yyyymmdd", "yyyy年mm月dd日");
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < closeacctno_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "3.自"+begdate+"起至"+enddate+"期间内注销的银行存款账户\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,closeacctno_colName);
						}
					break;
					case "[\"4\"]":
						if((int)json.get("creditloan_num") > 0){
							
							List result = (List)json.get("creditloan");
							String title = "4.本公司作为委托人的委托贷款\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,creditloan_colName);
						}else if((int)json.get("creditloan_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < creditloan_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "4.本公司作为委托人的委托贷款\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,creditloan_colName);
						}
					break;
					case "[\"5\"]":
						if((int)json.get("debtorloan_num") > 0){
							
							List result = (List)json.get("debtorloan");
							String title = "5.本公司作为借款人的委托贷款\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,debtorloan_colName);
						}else if((int)json.get("debtorloan_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < debtorloan_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "5.本公司作为借款人的委托贷款\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,debtorloan_colName);
						}
					break;
					case "[\"6.1\"]":
						if((int)json.get("ensurefavoree_num") > 0){
							
							List result = (List)json.get("ensurefavoree");
							String title = "6.担保\n（1）本公司为其他单位提供的、以贵行为担保受益人的担保\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,ensurefavoree_colName);	
						}else if((int)json.get("ensurefavoree_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < ensurefavoree_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "6.担保\n（1）本公司为其他单位提供的、以贵行为担保受益人的担保\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,ensurefavoree_colName);
						}
					break;
					case "[\"6.2\"]":
						if((int)json.get("givesecurity_num") > 0){
							
							List result = (List)json.get("givesecurity");
							String title = "6.担保\n（2）贵行向本公司提供的担保（如保函业务、备用信用证业务等）\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,givesecurity_colName);
						}else if((int)json.get("givesecurity_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < givesecurity_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "6.担保\n（2）贵行向本公司提供的担保（如保函业务、备用信用证业务等）\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,givesecurity_colName);
						}
					break;
					case "[\"7\"]":
						if((int)json.get("unpaidaccance_num") > 0){
							
							List result = (List)json.get("unpaidaccance");
							String title = "7.本公司为出票人且由贵行承兑而尚未支付的银行承兑汇票\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,unpaidaccance_colName);	
						}else if((int)json.get("unpaidaccance_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < unpaidaccance_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "7.本公司为出票人且由贵行承兑而尚未支付的银行承兑汇票\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,unpaidaccance_colName);	
						}
					break;
					case "[\"8\"]":
						if((int)json.get("notduetradebill_num") > 0){
							
							List result = (List)json.get("notduetradebill");
							String title = "8.本公司向贵行已贴现而尚未到期的商业汇票\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,notduetradebill_colName);		
						}else if((int)json.get("notduetradebill_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < notduetradebill_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "8.本公司向贵行已贴现而尚未到期的商业汇票\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,notduetradebill_colName);
						}
					break;
					case "[\"9\"]"://
						if((int)json.get("colltradebill_num") > 0){
							
							List result = (List)json.get("colltradebill");
							String title = "9.本公司为持票人且由贵行托收（或由本公司提示付款）的商业汇票\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,colltradebill_colName);	
						}else if((int)json.get("colltradebill_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < colltradebill_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "9.本公司为持票人且由贵行托收（或由本公司提示付款）的商业汇票\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,colltradebill_colName);	
						}
					break;
					case "[\"10\"]":
						if((int)json.get("irrofcredit_num") > 0){
							
							List result = (List)json.get("irrofcredit");
							String title = "10.本公司为申请人，由贵行开具的、未履行完毕的不可撤销信用证\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,irrofcredit_colName);		
						}else if((int)json.get("irrofcredit_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < irrofcredit_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "10.本公司为申请人，由贵行开具的、未履行完毕的不可撤销信用证\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,irrofcredit_colName);
						}
					break;
					case "[\"11\"]":
						if((int)json.get("foreigndealcon_num") > 0){
							
							List result = (List)json.get("foreigndealcon");
							String title = "11.本公司与贵行之间未履行完毕的外汇买卖合约\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,foreigndealcon_colName);	
						}else if((int)json.get("foreigndealcon_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < foreigndealcon_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "11.本公司与贵行之间未履行完毕的外汇买卖合约\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,foreigndealcon_colName);
						}
					break;
					case "[\"12\"]":
						if((int)json.get("secquityfile_num") > 0){
							
							List result = (List)json.get("secquityfile");
							String title = "12.本公司存放于贵行托管的证券或其他产权文件\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,secquityfile_colName);	
						}else if((int)json.get("secquityfile_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < secquityfile_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "12.本公司存放于贵行托管的证券或其他产权文件\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,secquityfile_colName);
						}
					break;
					case "[\"13\"]":
						if((int)json.get("notduefinalpro_num") > 0){
							
							List result = (List)json.get("notduefinalpro");
							String title = "13.本公司购买的由贵行发行的未到期银行理财产品\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,notduefinalpro_colName);
						}else if((int)json.get("notduefinalpro_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < notduefinalpro_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "13.本公司购买的由贵行发行的未到期银行理财产品\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,notduefinalpro_colName);
						}
					break;
					case "[\"14\"]":
						if((int)json.get("otherinfo_num") > 0){
							
							List result = (List)json.get("otherinfo");
							String title = "14.其他\n";
							List result1 = (List)json.get("otherinfo1");
							List result2 = (List)json.get("otherinfo2");
							List result3 = (List)json.get("otherinfo3");
							List result4 = (List)json.get("otherinfo4");
							List result5 = (List)json.get("otherinfo5");
							List result6 = (List)json.get("otherinfo6");
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,otherinfo_colName);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result1,otherinfo1_colName);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result2,otherinfo2_colName);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result3,otherinfo3_colName);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result4,otherinfo4_colName);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result5,otherinfo5_colName);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result6,otherinfo6_colName);
							System.out.print(_strToFile_);
						}else if((int)json.get("otherinfo_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < otherinfo_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "14.其他\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,otherinfo_colName);
							if((int)json.get("otherinfo1_num") == 0 && (int)json.get("otherinfo2_num") == 0 && (int)json.get("otherinfo3_num") == 0 && (int)json.get("otherinfo4_num") == 0 && (int)json.get("otherinfo5_num") == 0 && (int)json.get("otherinfo6_num") == 0){
								_strToFile_ = _strToFile_+"无\n";
							}else{
								if((int)json.get("otherinfo1_num") > 0){
									List result1 = (List)json.get("otherinfo1");
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result1,otherinfo1_colName);
								}else if((int)json.get("otherinfo1_num") == 0){
									List result1 = new ArrayList();
									List li1 = new ArrayList();
									for (int j = 1; j < otherinfo1_colName.size()+1; j++) {
										li1.add("无");
									}
									result1.add(li1);
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result1,otherinfo1_colName);	
								}
								if((int)json.get("otherinfo2_num") > 0){
									List result2 = (List)json.get("otherinfo2");
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result2,otherinfo2_colName);
								}else if((int)json.get("otherinfo2_num") == 0){
									List result2 = new ArrayList();
									List li2 = new ArrayList();
									for (int j = 1; j < otherinfo2_colName.size()+1; j++) {
										li2.add("无");
									}
									result2.add(li2);
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result2,otherinfo2_colName);	
								}
								if((int)json.get("otherinfo3_num") > 0){
									List result3 = (List)json.get("otherinfo3");
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result3,otherinfo3_colName);
								}else if((int)json.get("otherinfo3_num") == 0){
									List result3 = new ArrayList();
									List li3 = new ArrayList();
									for (int j = 1; j < otherinfo3_colName.size()+1; j++) {
										li3.add("无");
									}
									result3.add(li3);
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result3,otherinfo3_colName);	
								}
								if((int)json.get("otherinfo4_num") > 0){
									List result4 = (List)json.get("otherinfo4");
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result4,otherinfo4_colName);
								}else if((int)json.get("otherinfo4_num") == 0){
									List result4 = new ArrayList();
									List li4 = new ArrayList();
									for (int j = 1; j < otherinfo4_colName.size()+1; j++) {
										li4.add("无");
									}
									result4.add(li4);
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result4,otherinfo4_colName);	
								}
								if((int)json.get("otherinfo5_num") > 0){
									List result5 = (List)json.get("otherinfo5");
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result5,otherinfo5_colName);
								}else if((int)json.get("otherinfo5_num") == 0){
									List result5 = new ArrayList();
									List li5 = new ArrayList();
									for (int j = 1; j < otherinfo5_colName.size()+1; j++) {
										li5.add("无");
									}
									result5.add(li5);
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result5,otherinfo5_colName);	
								}
								if((int)json.get("otherinfo6_num") > 0){
									List result6 = (List)json.get("otherinfo6");
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result6,otherinfo6_colName);
								}else if((int)json.get("otherinfo6_num") == 0){
									List result6 = new ArrayList();
									List li6 = new ArrayList();
									for (int j = 1; j < otherinfo6_colName.size()+1; j++) {
										li6.add("无");
									}
									result6.add(li6);
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result6,otherinfo6_colName);	
								}
							}
							
							
							
							
						}
					break;
					case "[\"15\"]":
						logger.info("附表数据生成成功");
						if((int)json.get("cashconacctinfo_num") > 0){
							
							List result = (List)json.get("cashconacctinfo");
							String title = "附表.资金归集(资金池或其他资金管理)账户具体信息\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,cashconacctinfo_colName);		
						}else if((int)json.get("cashconacctinfo_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < cashconacctinfo_colName.size()+1; j++) {
								li.add("无");
							}
							result.add(li);
							String title = "附表.资金归集(资金池或其他资金管理)账户具体信息\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,cashconacctinfo_colName);
						}
					break;
					
				}

				
			}
			try {
				
							bufout = new BufferedWriter(new OutputStreamWriter(
									new FileOutputStream(file, true), csvEncode));
				
							bomByte = new byte[]{(byte)0xef,(byte)0xbb,(byte)0xbf};
							bomStr = new String(bomByte,csvEncode);
							bufout.write(bomStr);
//							_strToFile_ = _strToFile_.getBytes("utf-8").toString();
//							ss = _strToFile_.getBytes("GBK");
//							_strToFile_ = new String(ss,"GBK");
							bufout.write(_strToFile_);
							bufout.flush();
							return true;
						} catch (Exception e) {
							return false;
						} finally {
							if (bufout != null) {
								try {
									bufout.close();
								} catch (IOException e) {
								}
								bufout = null;
							}
						}
		}
		return true;

	}


	private static Paragraph getFont(int type,String text) throws DocumentException, IOException{
		//AppLogger.info("进入字体控制----------------"+type+text);
		BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		Font font = new Font(baseFont);
		font.setFamily("仿宋_GB2312");
		if(1 == type){//银行询证函
			font.setSize(16f);
			font.setStyle(Font.BOLD);
		}else if(2 == type){//正文
			font.setSize(10.5f);		
		}else if(3 == type){//左对齐
			font.setSize(10.5f);	
		}else if(4 == type){//右对齐
			font.setSize(10.5f);
		}else if(5 == type){//右对齐加粗
			font.setSize(9f);
			font.setStyle(Font.BOLD);
		}else{
			font.setSize(10.5f);			
		}
		
		Paragraph paragraph = new Paragraph(text,font);
		if(1 == type){
			paragraph.setAlignment(Paragraph.ALIGN_CENTER);//居中
			paragraph.setSpacingBefore(10f);//上间距
			paragraph.setSpacingAfter(10f);//下间距
		}else if(2 == type){
			paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
			paragraph.setFirstLineIndent(24);
			paragraph.setSpacingBefore(5f);
			paragraph.setSpacingAfter(10f);
		}else if(3 == type){
			paragraph.setAlignment(Element.ALIGN_LEFT);
			paragraph.setSpacingBefore(5f);
			paragraph.setSpacingAfter(5f);
		}else if(4 == type){
			paragraph.setAlignment(Element.ALIGN_RIGHT);
			paragraph.setSpacingBefore(5f);
			paragraph.setSpacingAfter(5f);
		}else if(5 == type){
			paragraph.setAlignment(Element.ALIGN_RIGHT);
			paragraph.setSpacingBefore(10f);
			paragraph.setSpacingAfter(10f);
		}
		return paragraph;
	}
	
	
	private static PdfPTable tableTemplates(List items,List colName) throws DocumentException, IOException{
		//AppLogger.info("***********************表格模板开始");
		PdfPTable inttable = new PdfPTable(colName.size());
		inttable.setWidthPercentage(100);//表格100%宽度填充
		inttable.setLockedWidth(false);//不固定宽度
		
		inttable.getDefaultCell().setLeading(1f, 1f);//单元格内文字行间距
		inttable.getDefaultCell().setBorderColor(new BaseColor(0, 0, 0));//边框颜色

		inttable.getDefaultCell().setUseAscender(true);//设置可以居中
		inttable.getDefaultCell().setMinimumHeight(20);////单元格内文字不确定个，不能设置成固定行高
//		inttable.setHeaderRows(1);//第一行做表头 会导致每一页开头都有表头
		inttable.setSplitLate(false);
		inttable.setSplitRows(true);
		
		if(colName.size() != 1){
			//表头
			for(int i=0; i<colName.size();i++){
				inttable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
				inttable.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);//设置垂直居中
				inttable.addCell(new Paragraph((String) colName.get(i),getTableFont()));
			}
			
			//表格每行
			for(int i=0; i < items.size(); i++){
				for(int j=0; j<((List)items.get(i)).size(); j++){
	                if(j == 0){
	                	inttable.getDefaultCell().setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.BOTTOM);                	
	                }else{
	                	inttable.getDefaultCell().setBorder(Rectangle.RIGHT | Rectangle.BOTTOM); 
	                }				
					if(j < colName.size()){	
						inttable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);//设置水平居中
						inttable.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);//设置垂直居中
						inttable.addCell(new Paragraph(((List)items.get(i)).get(j).toString(),getTableFont()));
					}
				}
			}
			
		}else{
			inttable.getDefaultCell().setBorder(Rectangle.TOP | Rectangle.LEFT | Rectangle.RIGHT | Rectangle.BOTTOM);
			inttable.addCell(new Paragraph(((List)items.get(0)).get(0).toString(),getTableFont()));
		}
		//AppLogger.info("***********************表格模板结束");
		return inttable;
		}
	
	
	/**
	 * 设置表格内部字体
	 * @param agrs
	 * @throws IOException 
	 * @throws DocumentException 
	 */
	private static Font getTableFont() throws DocumentException, IOException{
		BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		Font font = new Font(baseFont,10f,Font.NORMAL,new BaseColor(0, 0, 0)); 
		font.setFamily("仿宋_GB2312");
		return font;
	}
	
	/**
	 * @category 根据指定内容生成二维码图片
	 * @param qrCodeMsg
	 *            入参|待生成二维码的信息|{@link String}
	 * @param imgPath
	 *            入参|二维码图片路径|{@link String}
	 * @return 0 失败<br/>
	 *         1 成功<br/>
	 */
	/**@InParams(param = {
			@Param(name = "qrCodeMsg", comment = "待生成二维码的信息", type = java.lang.String.class),
			@Param(name = "imgPath", comment = "二维码图片路径，绝对路径，暂只支持jpg文件", type = java.lang.String.class) })
	@Returns(returns = { @Return(id = "0", desp = "失败"),
			@Return(id = "1", desp = "成功") })
	@Component(label = "根据指定内容生成二维码图片", style = "判断型", type = "同步组件", comment = "根据指定内容生成二维码图片", author = "zhuyulin", date = "2021-10-25 09:57:07")**/
	public static String createQRCodeImage(String qrCodeMsg, String imgPath) {
		try {
			BufferedImage image = createImage(qrCodeMsg, true, 100);
			// mkdirs(imgPath);
			ImageIO.write(image, "JPG", new File(imgPath));
		} catch (Exception e) {
			return "生成二维码图片发生异常，" + e.getMessage();
		}
		return "";
	}
	
	/**
	 * 根据指定内容生成二维码图片
	 * 
	 * @param content
	 *            待生成二维码的内容
	 * @param needCompress
	 *            是否需要压缩
	 * @param qrCodeSize
	 *            二维码图片大小
	 * @return
	 * @throws Exception
	 */
	private static BufferedImage createImage(String content,
			boolean needCompress, int qrCodeSize) throws Exception {
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		hints.put(EncodeHintType.MARGIN, 0);
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hints);
		int width = bitMatrix.getWidth();
		int height = bitMatrix.getHeight();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				if(bitMatrix.get(x, y)){
					image.setRGB(x, y, 0xFF000000);
				}else{
					image.setRGB(x, y, 0xFFFFFFFF);
				}
			}
		}
		return image;
	}
	
	
	/**
	 * @category 将图片合成到PDF指定位置
	 * @param qrCodeMsg
	 *            入参|待合成图片的位置集合|
	 *            {@link cn.com.agree.afa.svc.javaengine.context.JavaList}
	 * @param imgPath
	 *            入参|PDF文件路径|{@link String}
	 * @return 0 失败<br/>
	 *         1 成功<br/>
	 */
	/**@InParams(param = {
			@Param(name = "pdfPath", comment = "PDF文件路径，绝对路径", type = java.lang.String.class),
			@Param(name = "imgPath", comment = "待合成图片文件路径，绝对路径", type = java.lang.String.class),
			@Param(name = "pageNo", comment = "PDF文件页码", type = java.lang.Integer.class),
			@Param(name = "positions", comment = "待合成图片的PDF位置集合，一页中如有多个位置需合成图片，列表形式赋值，如：[[x1,y1],[x2,y2],[x3,y3]...]", type = cn.com.agree.afa.svc.javaengine.context.JavaList.class) })
	@Returns(returns = { @Return(id = "0", desp = "失败"),
			@Return(id = "1", desp = "成功") })
	@Component(label = "将图片合成到PDF指定位置", style = "判断型", type = "同步组件", comment = "将图片合成到PDF指定位置", author = "zhuyulin", date = "2021-11-07 10:57:07")**/
	public static String compositeImageToPDF(String pdfPath,
			String imgPath, Integer pageNo, List<Integer> positions) {
		PdfReader pdfReader = null;
		PdfStamper pdfStamper = null;
		FileOutputStream out = null;
		//String pdfbakpatch="/afabak/ERB/pdf/";
		try {
			File pdfFile = new File(pdfPath);
			if (!pdfFile.exists()) {
				return "PDF文件" + pdfPath
						+ "不存在，无法合成";
			}
			if (!pdfFile.isFile()) {
				return "PDF文件" + pdfPath
						+ "不是文件，无法合成";
			}
			File imgFile = new File(imgPath);
			if (!imgFile.exists()) {
				return "图片文件" + imgPath
						+ "不存在，无法合成";
			}
			if (!imgFile.isFile()) {
				return "图片文件" + imgPath
						+ "不是文件，无法合成";
			}
			if (positions == null || positions.size() == 0) {
				return "合成位置不能为空";
			}
			pdfReader = new PdfReader(pdfFile.getAbsolutePath());
			int pageNum = pdfReader.getNumberOfPages();
			String pdfName = pdfFile.getName();
			String tmpName = pdfName.substring(0, pdfName.lastIndexOf("."));

			if (pageNo < 1 || pageNo > pageNum) {
				return "页码超过PDF页数范围【"
						+ pageNo + "】，无法合成";
			}
//			AppLogger.info("电子印章合成");
			String tmpPath = new String(pdfPath);
			int index=0;
			for (int i = 0; i < positions.size(); i++) {
				index ++;
//				AppLogger.info("电子印章合成:::"+i);
				PdfReader pdfReader1 = null;
				PdfStamper pdfStamper1 = null;
				FileOutputStream out1 = null;
				try{
					Object position = positions.get(i);
					if (!(position instanceof List)) {
						if (positions.size() < 2) {
							return 
									"当入参positions列表不是嵌套列表时, 入参列表positions的长度不能小于2";
						}
						String tmpPath2 = new File(pdfFile.getParentFile(), tmpName
								+ "_"+index+".pdf").getAbsolutePath();
//						AppLogger.info("tmpPath2:"+tmpPath2);
						pdfReader1 = new PdfReader(tmpPath);
						out1 = new FileOutputStream(tmpPath2);
						pdfStamper1 = new PdfStamper(pdfReader, out1);
						PdfContentByte content = pdfStamper1.getOverContent(pageNo);
						Image image = Image.getInstance(imgPath);
						image.scaleToFit(150, 100);
//						AppLogger.info("合成印章图片开始");
						image.setAbsolutePosition((float) positions.get(0),
								(float) positions.get(1));
						content.addImage(image);
//						AppLogger.info("合成印章图片结束");
						pdfStamper1.close();
						out1.close();
						pdfReader1.close();
						tmpPath = tmpPath2;
						break;
					} else if (((List) position).size() < 2) {
						return 
								"入参positions列表的子元素的长度不能小于2";
					}
					String tmpPath2 = new File(	pdfFile.getParentFile(), tmpName+ "_"+index+".pdf").getAbsolutePath();
//					AppLogger.info("tmpPath2:"+tmpPath2);
					pdfReader1 = new PdfReader(tmpPath);
					out1 = new FileOutputStream(tmpPath2);
					pdfStamper1 = new PdfStamper(pdfReader1, out1);

					List tmpPosition = (List) position;
					PdfContentByte content = pdfStamper1.getOverContent(pageNo);
					Image image = Image.getInstance(imgPath);
					image.scaleToFit(150, 100);
					image.setAbsolutePosition((float) tmpPosition.get(0),(float) tmpPosition.get(1));
					content.addImage(image);
					pdfStamper1.close();
					out1.close();
					pdfReader1.close();
					tmpPath = tmpPath2;
//					AppLogger.info("电子印章合成:::结束");
				}catch (Exception e) {
					return "电子印章合成到回单PDF文件发生异常，" + e.getMessage();
				} finally {
					closeResource(pdfStamper1, out1, pdfReader1);
				}
			}
			pdfReader.close();
			
			if (index > 0) {
				String filePatch0 = new File(pdfFile.getParentFile(), tmpName
						+ "_" + 0 + ".pdf").getAbsolutePath();
//				AppLogger.info(filePatch0);
				boolean flag = pdfFile.renameTo(new File(filePatch0));
//				AppLogger.info(flag);
				String filePatch2 = new File(pdfFile.getParentFile(), tmpName
						+ "_" + index + ".pdf").getAbsolutePath();
//				AppLogger.info(filePatch2);
				//JavaList argList=new JavaList();
				//linux 命令
				/*String cmd = "cp "+filePatch2+" "+pdfPath;
				AppLogger.info("文件复制："+cmd);
				TCResult c=P_Cmd.systemCall(cmd, argList);*/
				boolean flag1 = new File(filePatch2)
				.renameTo(new File(pdfPath));

				/*String filePatch2 = new File(pdfbakpatch, tmpName
						+ "_" + index + ".pdf").getAbsolutePath();
				AppLogger.info(filePatch2);
				JavaList argList=new JavaList();
				//linux 命令
				String cmd = "cp -f "+filePatch2+" "+pdfPath;
				AppLogger.info("文件复制："+cmd);
				TCResult c=P_Cmd.systemCall(cmd, argList);
				AppLogger.info(c.getStatus());

				String rm = "rm "+pdfbakpatch+tmpName+"_*";
				AppLogger.info("文件删除"+rm);
				TCResult b=P_Cmd.systemCall(rm, argList);
				AppLogger.info(b.getStatus());*/
			}
//			AppLogger.info("电子印章合成结束");
		} catch (Exception e) {

			return "图片合成到PDF文件发生异常，" + e.getMessage();
		} finally {
			closeResource(pdfStamper, out, pdfReader);
		}
		return "";
	}
	
	private static void closeResource(PdfStamper pdfStamper,
			FileOutputStream out, PdfReader pdfReader) {
		try {
			if (pdfStamper != null) {
				pdfStamper.close();
			}
			if (out != null) {
				out.close();
			}
			if (pdfReader != null) {
				pdfReader.close();
			}
		} catch (Exception e) {
//			AppLogger.error("关闭资源发生异常");
//			AppLogger.error(e);
		}
	}
	
	
	private static String tableTemplatesCsv(File file,String csvEncode,String title,List result,List colName) throws IOException{
		String _strToFile_ = "";
		if(title.equals("")){
			_strToFile_ = "";
		}else{
			_strToFile_ = title;
		}
		
//		byte[] bomByte = null;
//		String bomStr = "";
//		BufferedWriter bufout = null;
		if(colName.size() != 1){
			//表头
			for(int j=0; j<colName.size();j++){
				_strToFile_ = _strToFile_ + colName.get(j)+",";

			}
			_strToFile_ = _strToFile_ + "\n";
//			List result = (List)json.get("bankdeposit");
			for(int o=0; o<result.size();o++){
				_strToFile_ = _strToFile_ + result.get(o)+",\n";
				_strToFile_ = _strToFile_.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\"", "	");
			}
//			System.out.print("2222222");
//			System.out.print(_strToFile_);
		}else if(colName.size() == 1){
			if(colName.get(0).equals("其他")||colName.get(0).equals("Other")){
				
			}else{
				_strToFile_ = _strToFile_ + colName.get(0)+",\n";
				_strToFile_ = _strToFile_ + result.get(0)+",\n";
				_strToFile_ = _strToFile_.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\"", "	");
			}
			
		}else{
//			inttable.getDefaultCell().setBorder(Rectangle.TOP | Rectangle.LEFT | Rectangle.RIGHT | Rectangle.BOTTOM);
//			inttable.addCell(new Paragraph(((List)items.get(0)).get(0).toString(),getTableFont()));
		}

		return _strToFile_;
		}
	
	
	
	public static void main(String[] args) throws Exception {
		BpbcCsvSerevice ca = new BpbcCsvSerevice();
		List<Integer> colName = new ArrayList();
		colName.add(480);
		colName.add(699);
		String ss = ca.createQRCodeImage("http://www.baidu.com","C:\\Users\\A9010011\\Desktop\\需求\\c.jpg");
		ca.compositeImageToPDF("C:\\Users\\A9010011\\Desktop\\需求\\c.pdf", "C:\\Users\\A9010011\\Desktop\\需求\\c.jpg", 1, colName);
		System.out.println(ss);
	}


	@Override
	public boolean createEngCsv(JSONObject json) throws Exception {
		//AppLogger.info("业务日期---------：" + busi_date);
		//AppLogger.info("函证编号---------：" + confirmno);
		//AppLogger.info("会计师事务所名称---------：" + tenantname);
		//AppLogger.info("起始日期---------：" + startdate);
		//AppLogger.info("截止日期---------：" + enddate);
		//AppLogger.info("单位名称---------：" + organizationname);
		//AppLogger.info("函证项信息---------：" + String.valueOf(values));
		
		//*************************生成PDF文件
		//AppLogger.info("*************************生成PDF文件start");
		//页面大小
		String hzbh = (String) json.get("hzbh");//函证编号
		String recvdate = (String) json.get("recvdate");//函证接收日期
		String organizationname = (String) json.get("organizationname");//单位名称
		String tenantname = (String) json.get("tenantname");//会计师事务所名称
		System.out.print("函证编号---------：" + hzbh);
		System.out.print("函证编号---------：" + json);
		
		String confirmbegindate = (String) json.get("confirmbegindate");//起始日期
		String confirmenddate = (String) json.get("confirmenddate");//截止日期
		String pdffilepath = (String) json.get("pdffilepath");//文件目录
		String csvEncode = (String) json.get("csvEncode");//文件编码

		String startdate;
		String busi_date = null;
		Rectangle rect = new Rectangle(PageSize.A4);//文档竖向
//		String outputfilePath = "C:/Users/A9010012/Desktop";
		//String outputfilePath = pdffilepath+hzbh+".csv";
		String flag = (String) json.get("flag");//文件目录
		String outputfilePath = "";
		if(flag.equals("update")){
			outputfilePath = pdffilepath+"(update)"+hzbh+".csv";
		}else{
			outputfilePath = pdffilepath+hzbh+".csv";
		}
		byte[] bomByte = null;
		String bomStr = "";

		//如果没有则创建
		File saveDir = new File(outputfilePath);
		File dir = saveDir.getParentFile();
		if(!dir.exists()){
			dir.mkdirs();			
		}
		
		File file = new File(outputfilePath);
		String _strToFile_ = "";
		BufferedWriter bufout = null;
		boolean append = false;
		if (file.exists()) {
			append = true;
		}
		
		if(json != null && !json.equals("{}")){
			PdfPTable table = null;
//			List result = null;
			//银行存款函证
			List bankdeposit_colName = Arrays.asList("Account Name","Account No.","Currency","Interest Rate","Account Type","Balance","Fund Collection Account (fund pool or other fund management)  (Y/N)","Start Date","Due Date","Usage Restraint (Frozen， Secured， Pledged or any other restriction)","Remarks");
			//银行借款函证
			List bankloan_colName = Arrays.asList("Borrower","Account No.","Currency","Balance","Starting Date","Due Date","Interest Rate","Security or Guarantor","Remarks");
			//期间注销账户函证
			List closeacctno_colName = Arrays.asList("Account Name","Account No.","Currency","Account Closure Date");
			//公司贷款方委托贷款函证
			List creditloan_colName = Arrays.asList("Account Name","Account No.","Borrower","Currency","Interest Rate","Balance","Starting and Due Date","Remarks");
			//公司借款方委托贷款函证
			List debtorloan_colName = Arrays.asList("Account Name","Account No.","Fund User","Currency","Interest Rate","Balance","Starting and Due Date","Remarks");
			//银行受益人担保函证
			List ensurefavoree_colName = Arrays.asList("Party Guaranteed","Type of Guarantee","Currency","Amount Guaranteed","Due Date of Guarantee","Guarantee Contract No.","Remarks");
			//银行担保函证
			List givesecurity_colName = Arrays.asList("Party Guaranteed","Type of Guarantee","Currency","Amount Guaranteed","Due Date of Guarantee","Guarantee Contract No.","Remarks");
			//未支付银行承兑汇票函证
			List unpaidaccance_colName = Arrays.asList("Bank Acceptance No.","Settlement Account No.","Currency","Par Value","Date of  Draft","Expiry Date","Collateral/Pledge");
			//未到期商业汇票函证
			List notduetradebill_colName = Arrays.asList("Trade Bill No.","Acceptor","Currency","Par Value","Date of  Draft","Expiry Date","Discount Date","Discount Rate","Net Value after Discount");
			//银行托收商业汇票函证
			List colltradebill_colName = Arrays.asList("Trade Bill No.","Acceptor","Currency","Par Value","Date of Draft","Expiry Date");
			//不可撤销信用证函证
			List irrofcredit_colName = Arrays.asList("L/C No.","Beneficiary","Currency","Amount","Expiry Date","Unutilized Amount");
			//外汇买卖合约函证
			List foreigndealcon_colName = Arrays.asList("Type","Contract No.","Bank’s Selling Currency","Bank’s Buying Currency","Unfulfilled Contract Amount","Exchange Rate","Delivery Date");
			//证券产权文件函证
			List secquityfile_colName = Arrays.asList("Name of Securities and Other Property Right Documents","Document No.","Quantity","Currency","Amount");
			//未到期银行理财产品函证
			List notduefinalpro_colName = Arrays.asList("Name of  Products","Type of Products","Currency","Shares Held","Net Product Value","Purchase Date","Expiry Date","Usage Restraint (Frozen， Secured， Pledged or any other restriction)");
			//资金归集账户信息函证
			List cashconacctinfo_colName = Arrays.asList("No.","Name of Fund Provider","Bank Account No. of Fund Provider","Name of Fund User","Bank Account No. of Fund User","Currency","Balance on Confirmation Date(Positive for outflow and negative for inflow)","Remarks");
			//其他函证
			List otherinfo_colName = Arrays.asList("Other");
			
			
			//其他函证1
			List otherinfo1_colName = Arrays.asList("Customer Name","Type","Contract No.","Bank’s Payment Currency ","Bank’s Charge Currency ","Unfulfilled Contract Amount","Expiry Date");
			//其他函证2
			List otherinfo2_colName = Arrays.asList("Customer Name","Type","Contract No.","Option Structure","Unfulfilled Contract Currency","Unfulfilled Contract Amount","Strike Price","Expiry Date");
			//其他函证3
			List otherinfo3_colName = Arrays.asList("Customer Name","Type","Contract No.","Bank’s Payment Rate","Bank’s Charge Rate","Unfulfilled Contract Currency","Unfulfilled Contract Amount","Expiry Date");
			//其他函证4
			List otherinfo4_colName = Arrays.asList("Customer Name","Type","Contract No.","Option Structure","Unfulfilled Contract Currency","Unfulfilled Contract Amount","Strike Price","Expiry Date");
			//其他函证5
			//List otherinfo5_colName = Arrays.asList("借款人名称","借款账号","币种","余额","借款日期","到期日期","利率","抵(质)押品担保人","备注");
			List otherinfo5_colName = Arrays.asList("Borrower","Account No.","Currency","Balance","Value  Date","Maturity Date","Interest Rate","Security or Guarantor","Remarks");
			
			//其他函证6
			List otherinfo6_colName = Arrays.asList("Remarks");
//			System.out.print(json.get("bankdeposit_num"));
			
			for (int i = 0; i < (int)json.get("hzxnum"); i++) {
				List a = (List)json.get("hzxinfo");
				
//				System.out.print("******"+a.get(i).toString().replace("[", "").replace("]", "").replace("\"", ""));
//				System.out.print("******"+a.get(i).toString().replace("[", "").replace("]", "").replace("\"", ""));
//				switch(a.get(i).toString().replace("[", "").replace("]", "").replace("\"", "")){
				switch(a.get(i).toString()){
					case "[\"1\"]":
						if((int)json.get("bankdeposit_num") > 0){
							String title = "1.Bank Deposit\n";
							List result = (List)json.get("bankdeposit");
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,bankdeposit_colName);
						}else if((int)json.get("bankdeposit_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							String title = "1.Bank Deposit\n";
							for (int j = 1; j < bankdeposit_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,bankdeposit_colName);
						}
					break;
					case "[\"2\"]":
						if((int)json.get("bankloan_num") > 0){
							List result = (List)json.get("bankloan");
							String title = "2.Bank Loan\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,bankloan_colName);
						}else if((int)json.get("bankloan_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < bankloan_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "2.Bank Loan\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,bankloan_colName);
						}
					break;
					case "[\"3\"]":
						if((int)json.get("closeacctno_num") > 0){
							
							List result = (List)json.get("closeacctno");
							String title = "3.during "+confirmbegindate+"to"+confirmenddate+"Accounts closed\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,closeacctno_colName);
						}else if((int)json.get("closeacctno_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < closeacctno_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "3.during"+confirmbegindate+"to"+confirmenddate+"Accounts closed\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,closeacctno_colName);
						}
					break;
					case "[\"4\"]":
						if((int)json.get("creditloan_num") > 0){
							
							List result = (List)json.get("creditloan");
							String title = "4.Designated Deposits\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,creditloan_colName);
						}else if((int)json.get("creditloan_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < creditloan_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "4.Designated Deposits\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,creditloan_colName);
						}
					break;
					case "[\"5\"]":
						if((int)json.get("debtorloan_num") > 0){
							
							List result = (List)json.get("debtorloan");
							String title = "5.Designated Loans\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,debtorloan_colName);
						}else if((int)json.get("debtorloan_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < debtorloan_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "5.Designated Loans\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,debtorloan_colName);
						}
					break;
					case "[\"6.1\"]":
						if((int)json.get("ensurefavoree_num") > 0){
							
							List result = (List)json.get("ensurefavoree");
							String title = "6.Guarantees\n（1）Given by you on our behalf\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,ensurefavoree_colName);	
						}else if((int)json.get("ensurefavoree_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < ensurefavoree_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "6.Guarantees\n（1）Given by you on our behalf\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,ensurefavoree_colName);
						}
					break;
					case "[\"6.2\"]":
						if((int)json.get("givesecurity_num") > 0){
							
							List result = (List)json.get("givesecurity");
							String title = "6.Guarantees\n（2）Given by us on your behalf\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,givesecurity_colName);
						}else if((int)json.get("givesecurity_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < givesecurity_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "6.Guarantees\n（2）Given by us on your behalf\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,givesecurity_colName);
						}
					break;
					case "[\"7\"]":
						if((int)json.get("unpaidaccance_num") > 0){
							
							List result = (List)json.get("unpaidaccance");
							String title = "7.Acceptances outstanding per our bank\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,unpaidaccance_colName);	
						}else if((int)json.get("unpaidaccance_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < unpaidaccance_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "7.Acceptances outstanding per our bank\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,unpaidaccance_colName);	
						}
					break;
					case "[\"8\"]":
						if((int)json.get("notduetradebill_num") > 0){
							
							List result = (List)json.get("notduetradebill");
							String title = "8.Trade bills purchased by our bank and outstanding at confirmation date\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,notduetradebill_colName);		
						}else if((int)json.get("notduetradebill_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < notduetradebill_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "8.Trade bills purchased by our bank and outstanding at confirmation date\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,notduetradebill_colName);
						}
					break;
					case "[\"9\"]":
						if((int)json.get("colltradebill_num") > 0){
							
							List result = (List)json.get("colltradebill");
							String title = "9.Trade bills held by our bank for collection\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,colltradebill_colName);	
						}else if((int)json.get("colltradebill_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < colltradebill_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "9.Trade bills held by our bank for collection\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,colltradebill_colName);	
						}
					break;
					case "[\"10\"]":
						if((int)json.get("irrofcredit_num") > 0){
							
							List result = (List)json.get("irrofcredit");
							String title = "10.Irrevocable letters of credit outstanding per our bank\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,irrofcredit_colName);		
						}else if((int)json.get("irrofcredit_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < irrofcredit_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "10.Irrevocable letters of credit outstanding per our bank\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,irrofcredit_colName);
						}
					break;
					case "[\"11\"]":
						if((int)json.get("foreigndealcon_num") > 0){
							
							List result = (List)json.get("foreigndealcon");
							String title = "11.Outstanding foreign exchange contract\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,foreigndealcon_colName);	
						}else if((int)json.get("foreigndealcon_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < foreigndealcon_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "11.Outstanding foreign exchange contract\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,foreigndealcon_colName);
						}
					break;
					case "[\"12\"]":
						if((int)json.get("secquityfile_num") > 0){
							
							List result = (List)json.get("secquityfile");
							String title = "12.Securities and other property right documents placed at bank\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,secquityfile_colName);	
						}else if((int)json.get("secquityfile_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < secquityfile_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "12.Securities and other property right documents placed at bank\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,secquityfile_colName);
						}
					break;
					case "[\"13\"]":
						if((int)json.get("notduefinalpro_num") > 0){
							
							List result = (List)json.get("notduefinalpro");
							String title = "13.Unexpired financial products owed by you per our bank\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,notduefinalpro_colName);
						}else if((int)json.get("notduefinalpro_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < notduefinalpro_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "13.Unexpired financial products owed by you per our bank\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,notduefinalpro_colName);
						}
					break;
					case "[\"14\"]":
						if((int)json.get("otherinfo_num") > 0){
							
							List result = (List)json.get("otherinfo");
							String title = "14.Other Matters\n";
							List result1 = (List)json.get("otherinfo1");
							List result2 = (List)json.get("otherinfo2");
							List result3 = (List)json.get("otherinfo3");
							List result4 = (List)json.get("otherinfo4");
							List result5 = (List)json.get("otherinfo5");
							List result6 = (List)json.get("otherinfo6");
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,otherinfo_colName);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result1,otherinfo1_colName);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result2,otherinfo2_colName);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result3,otherinfo3_colName);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result4,otherinfo4_colName);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result5,otherinfo5_colName);
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result6,otherinfo6_colName);
							System.out.print(_strToFile_);
						}else if((int)json.get("otherinfo_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < otherinfo_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "14.Other Matters\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,otherinfo_colName);	
							
							if((int)json.get("otherinfo1_num") == 0 && (int)json.get("otherinfo2_num") == 0 && (int)json.get("otherinfo3_num") == 0 && (int)json.get("otherinfo4_num") == 0 && (int)json.get("otherinfo5_num") == 0 && (int)json.get("otherinfo6_num") == 0){
								_strToFile_ = _strToFile_+"none \n";
							}else{
								if((int)json.get("otherinfo1_num") > 0){
									List result1 = (List)json.get("otherinfo1");
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result1,otherinfo1_colName);
								}else if((int)json.get("otherinfo1_num") == 0){
									List result1 = new ArrayList();
									List li1 = new ArrayList();
									for (int j = 1; j < otherinfo1_colName.size()+1; j++) {
										li1.add("none");
									}
									result1.add(li1);
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result1,otherinfo1_colName);	
								}
								if((int)json.get("otherinfo2_num") > 0){
									List result2 = (List)json.get("otherinfo2");
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result2,otherinfo2_colName);
								}else if((int)json.get("otherinfo2_num") == 0){
									List result2 = new ArrayList();
									List li2 = new ArrayList();
									for (int j = 1; j < otherinfo2_colName.size()+1; j++) {
										li2.add("none");
									}
									result2.add(li2);
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result2,otherinfo2_colName);	
								}
								if((int)json.get("otherinfo3_num") > 0){
									List result3 = (List)json.get("otherinfo3");
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result3,otherinfo3_colName);
								}else if((int)json.get("otherinfo3_num") == 0){
									List result3 = new ArrayList();
									List li3 = new ArrayList();
									for (int j = 1; j < otherinfo3_colName.size()+1; j++) {
										li3.add("none");
									}
									result3.add(li3);
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result3,otherinfo3_colName);	
								}
								if((int)json.get("otherinfo4_num") > 0){
									List result4 = (List)json.get("otherinfo4");
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result4,otherinfo4_colName);
								}else if((int)json.get("otherinfo4_num") == 0){
									List result4 = new ArrayList();
									List li4 = new ArrayList();
									for (int j = 1; j < otherinfo4_colName.size()+1; j++) {
										li4.add("none");
									}
									result4.add(li4);
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result4,otherinfo4_colName);	
								}
								if((int)json.get("otherinfo5_num") > 0){
									List result5 = (List)json.get("otherinfo5");
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result5,otherinfo5_colName);
								}else if((int)json.get("otherinfo5_num") == 0){
									List result5 = new ArrayList();
									List li5 = new ArrayList();
									for (int j = 1; j < otherinfo5_colName.size()+1; j++) {
										li5.add("none");
									}
									result5.add(li5);
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result5,otherinfo5_colName);	
								}
								if((int)json.get("otherinfo6_num") > 0){
									List result6 = (List)json.get("otherinfo6");
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result6,otherinfo6_colName);
								}else if((int)json.get("otherinfo6_num") == 0){
									List result6 = new ArrayList();
									List li6 = new ArrayList();
									for (int j = 1; j < otherinfo6_colName.size()+1; j++) {
										li6.add("none");
									}
									result6.add(li6);
									_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, "",result6,otherinfo6_colName);	
								}
							}
							
							
						}
					break;
					case "[\"15\"]":
						if((int)json.get("cashconacctinfo_num") > 0){
							
							List result = (List)json.get("cashconacctinfo");
							String title = "Attached list Information of Fund Collection (fund pool or other fund management) Accounts\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,cashconacctinfo_colName);		
						}else if((int)json.get("cashconacctinfo_num") == 0){
							List result = new ArrayList();
							List li = new ArrayList();
							for (int j = 1; j < cashconacctinfo_colName.size()+1; j++) {
								li.add("none");
							}
							result.add(li);
							String title = "Attached list Information of Fund Collection (fund pool or other fund management) Accounts\n";
							_strToFile_ = _strToFile_ + tableTemplatesCsv(file,csvEncode, title,result,cashconacctinfo_colName);
						}
					break;
					
				}

				
			}
			try {
				
							bufout = new BufferedWriter(new OutputStreamWriter(
									new FileOutputStream(file, true), csvEncode));
				
							bomByte = new byte[]{(byte)0xef,(byte)0xbb,(byte)0xbf};
							bomStr = new String(bomByte,csvEncode);
							bufout.write(bomStr);
//							_strToFile_ = _strToFile_.getBytes("utf-8").toString();
//							ss = _strToFile_.getBytes("GBK");
//							_strToFile_ = new String(ss,"GBK");
							bufout.write(_strToFile_);
							bufout.flush();
							return true;
						} catch (Exception e) {
							return false;
						} finally {
							if (bufout != null) {
								try {
									bufout.close();
								} catch (IOException e) {
								}
								bufout = null;
							}
						}
		}
		return true;
	}
	

}
